package teacher

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
	"strings"
)

func (h THandler) SearchTeacherToWx(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.SearchTeacherReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Teacher:SearchTeacher with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Teacher:SearchTeacher with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//查找
	teachers, count, err := h.M.TeacherQueryGrade(req.Grade)
	if err != nil {
		zap.L().Error("Teacher:SearchTeacherToWx h.M.TeacherQueryGrade err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.Count = count
	resp.Data = teachers
	resp.SendSuccess(c)
}
func (h THandler) SearchTeacherToWxClass(c *gin.Context) {
	var classes []*models.ClassInfo
	resp := new(models.RespData)
	req := new(models.SearchTeacherClassReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Teacher:SearchTeacher with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Teacher:SearchTeacher with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//查找
	exist, info, err := h.M.TeacherCheckExistByID(strconv.Itoa(req.TeacherId))
	if err != nil {
		zap.L().Error("Teacher:SearchTeacherToWx h.M.TeacherQueryGrade err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		//查班级
		class := strings.Split(info.ClassList, "|")
		for _, v := range class {
			if v == "" {
				continue
			}
			exist, classInfo, err := h.M.ClassCheckExistByID(v)
			if err != nil {
				zap.L().Error("Teacher:SearchTeacherToWx h.M.TeacherQueryGrade err", zap.Error(err))
			}
			if exist {
				classes = append(classes, classInfo)
			}
		}
	}
	if len(classes) != 0 {
		resp.Data = classes
	}
	resp.SendSuccess(c)
}
